<?php


/**
 * 用户的答题记录入库
 */

namespace App\Jobs;

use App\Models\Qh_Question;
use App\Models\Qh_Rank;
use App\Models\User;
use App\Service\Redis\RedisBaseService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class UserQuestionLearnLogToDbJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected Qh_Question $question;
    protected int $userId;
    protected array $params;
    protected int $mode;    // 模式，1：刷题、2：刷题-小题、3、考试模式

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userId, $question, $params, $mode)
    {
        $this->question = $question;
        $this->userId = $userId;
        $this->params = $params;
        $this->mode = $mode;
    }

    /**
     * Execute the job.
     *
     * @param RedisBaseService $redisBaseService
     * @return void
     * @throws \Throwable
     */
    public function handle(RedisBaseService $redisBaseService)
    {
        if ($this->mode == 3) {
            $tableName = 'qh_user_kaoshi_question_logs';
        }else {
            $tableName = 'qh_user_question_logs';
        }

        DB::transaction(function () use ($tableName, $redisBaseService){
            try {
                DB::table($tableName)->updateOrInsert([
                    'userId' => $this->userId,
                    'questionId' => $this->question->id
                ], [
                    'userAnswer' => $this->params['answer'],
                    'result' => $this->params['result'],
                    'qlId' => $this->question->qlId,
                    'courseId' => $this->question->courseId,
                    'knowledgeId' => $this->question->knowledgeId,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);

                // 答题模式
                if ($this->mode == 1) {
                    // 记录学习状态START
                    $learn = DB::table('qh_user_learn')
                        ->where('userId', $this->userId)
                        ->where('courseId', $this->question->courseId)
                        ->where('knowledgeId', $this->question->knowledgeId)
                        ->first();
                    if (!$learn) {
                        DB::table('qh_user_learn')->insert([
                            'userId' => $this->userId,
                            'qlId' => $this->question->qlId,
                            'courseId' => $this->question->courseId,
                            'knowledgeId' => $this->question->knowledgeId,
                            'qCount' => 1,
                            'created_at' => Carbon::now()
                        ]);
                    } else {
                        DB::table('qh_user_learn')
                            ->where('userId', $this->userId)
                            ->where('courseId', $this->question->courseId)
                            ->where('knowledgeId', $this->question->knowledgeId)
                            ->update([
                                'qCount' => $learn->qCount + 1,
                                'updated_at' => Carbon::now()
                            ]);
                    }
                    // 记录学习状态END
// -----------------------------------------------------------------------------------
                    // 排名
                    $rank = Qh_Rank::where('userId', $this->userId)->first();
                    if (!$rank) {
                        $rank = new Qh_Rank();
                        $rank->userId = $this->userId;
                    }
                    // 正确
                    if ($this->params['result'] == 1) {
                        // 更新正确次数
                        $this->question->rightCount += 1;
                        $rank->rightCount += 1;

                        // 错题出库
                        $redisBaseService->popWrongOrCollectQuestion($this->userId, $this->question, 1);
                    }
                    // 错误
                    if ($this->params['result'] == 2) {
                        // 更新错误次数
                        $this->question->wrongCount += 1;
                        $rank->wrongCount += 1;

                        // 错题入库
                        $redisBaseService->pushWrongOrCollectQuestionToDb($this->userId, $this->question, 1);
                    }
                    $rank->save();
                    $this->question->save();

                    /**
                     * 更新答题数量
                     */
                    $user = User::find($this->userId);
                    $allCount = $redisBaseService->getUserStatisticsData('statistics:userLearnQuestionCount', $user->id)??$user->learnQuestionCount;
                    $todayCount = 1;

                    if ($user->learnQuestionOfLastTime == null || !Carbon::parse($user->learnQuestionOfLastTime)->isToday()) {
                        $user->learnQuestionOfLastTime = Carbon::now();
                        $user->correctQuestionCountOfToday = 0;
                        $user->wrongQuestionCountOfToday = 0;
                    }else {
                        $todayCount = $redisBaseService->getUserStatisticsData('statistics:userLearnQuestionOfTodayCount', $user->id)??$user->learnQuestionCountOfToday;
                    }

                    // 更新用户表的答题数量
                    $user->learnQuestionCount = $allCount;
                    $user->learnQuestionCountOfToday = $todayCount;
                    if ($this->params['result'] == 1) {
                        $user->correctQuestionCount += 1;
                        $user->correctQuestionCountOfToday += 1;
                    }elseif ($this->params['result'] == 2) {
                        $user->wrongQuestionCount += 1;
                        $user->wrongQuestionCountOfToday += 1;
                    }

                    $user->save();
                }
            }catch (\Exception $e) {
                \Log::error($e->getMessage());
                \Log::error('[答题助手]处理异常', [
                    'userId' => $this->userId,
                    'questionId' => $this->question->id,
                    'params' => $this->params
                ]);
            }
        }, 5);
        \Log::debug('[答题助手]处理完成', [
            'mode' => $this->mode,
            'userId' => $this->userId,
            'questionId' => $this->question->id,
        ]);
    }
}
